from io import BytesIO
from fastapi import FastAPI, UploadFile, Form
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from starlette.responses import JSONResponse, RedirectResponse
from pydantic import BaseModel

from typing import List, Optional

# from starlette.staticfiles import StaticFiles

from src.FilesAgent import receive_messages_and_files, receive_request_history
from src.chatAI import MyHistoryLoader
from src.custom.tools import logger, set_logger
from src.file_parsers.FileManage import get_file_cache_dict_by_
from src.user import UserInfo

set_logger()
app = FastAPI()
app.mount("/static", StaticFiles(directory="../static"), name="static")


class PageInfo(BaseModel):
    file_path: str
    block_info: list

@app.get("/")
async def redirect_to_inner_highlight():
    # return RedirectResponse(url="/static/pdf_view/inner_highlight.html")
    return RedirectResponse(url="/static/pdf_view/index.html")
@app.post("/upload-pdf")
async def upload_pdf(message: Optional[str] = Form(None),
                     files: Optional[List[UploadFile]] = Form(None),
                     current_page_n: Optional[int] = Form(None),):

    page_info = {"file_path": "", "block_info": []}
    if message:
        logger.debug(f"received message: {message}")
    else:
        message = "简述一下这个文件的内容"

    dont_have_a_file = True
    if files:
        for file in files:
            if file.size == 0: continue
    # 接收的files不是空的，需要size判断
            dont_have_a_file = False
            logger.debug(f"received file name: {file.filename}")
            file_bytes = await file.read()
            page_info = receive_messages_and_files(message,
                                                   file_bytes,
                                                   file_name = file.filename,
                                                   current_page_n=current_page_n)
            break  # 如果有多个文件，只处理第一个
        # 防止文件size都为0
        if dont_have_a_file:
            page_info = {
                "file_path": "",
                "block_info": [
                    {"text": "文件大小都为0", "order": [], "coords": []}
                ]
            }
            return page_info
    else:
        # 没有文件的情况
        logger.debug("No files received")
        page_info = receive_messages_and_files(message, None, current_page_n=current_page_n)

    try:
        return page_info
    except Exception as e:
        return JSONResponse(status_code=500, content={"error": str(e)})

@app.get("/getHistory")
async def get_history():
    return receive_request_history()


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8001)